package com.example.securitylianxi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.securitylianxi.domain.AuthUser;
import com.example.securitylianxi.domain.LoginUser;
import com.example.securitylianxi.service.AuthUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private BCryptPasswordEncoder pw;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<AuthUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthUser::getUsername, username);
        AuthUser authUser = authUserService.getOne(wrapper);
        if (Objects.isNull(authUser)) {
            throw new UsernameNotFoundException("用户名或者密码不存在");
        }
        return new LoginUser(authUser, AuthorityUtils.commaSeparatedStringToAuthorityList(authUser.getUserAuth()));
    }
}
